'use strict';
/**
 * @fileoverview 总军团
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var autoIncrement = require('mongoose-auto-increment');
var dataApi = require('../libs/dataApi');
var unionGroupMgr = require('../mgr/unionGroupMgr.js');
var unionTechConf = require('../config/unionTechConf.js');

var _time = function () {
    return moment().unix();
};

// 初始化联盟科技

var _initialUnionTech = function () {
    var list = [];
    var tech_list = unionTechConf.getUnionTechIdConf();
    _.each(tech_list, function (value) {
        list.push({
            tech_id: value.id,
            exp: 0,
            lvl: 0,
            star: 0,
            type: value.type
        });
    });
    return list;
};
///////////////////////////////////////////////////////////
/**
 * 公会申请记录
 * @type {mongoose}
 */
var applyItemSchema = new mongoose.Schema({
    // 公会ID
    role_id: {
        type: Number
    },

    // 申请时间
    create_time: {
        type: Date,
        default: 0
    }
});

if (!applyItemSchema.options.toJSON) {
    applyItemSchema.options.toJSON = {};
}
/* jshint unused:false */
applyItemSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

///////////////////////////////////////////////////////////

/**
 * 公会申请记录
 * @type {mongoose}
 */
var unionTechSchema = new mongoose.Schema({
    // 联盟科技
    tech_id: {
        type: Number,
        required: true
    },

    // 技能经验
    exp: {
        type: Number,
        default: 0
    },

    // 技能等级
    lvl: {
        type: Number,
        default: 0
    },
    //
    // 技能星级
    star: {
        type: Number,
        default: 0
    },

    // 技能类型
    type: {
        type: Number,
        default: 0
    }
});

if (!unionTechSchema.options.toJSON) {
    unionTechSchema.options.toJSON = {};
}

/**
 * 增加联盟科技经验
 * @return {[type]} [description]
 */
unionTechSchema.methods.addExp = function (exp_num) {
    var max_star = unionTechConf.getTypeByStar(this.tech_id);
    var lvl = this.lvl;
    var star = this.star;
    var next_up_exp_conf = unionTechConf.getTechGainConf(this.tech_id, lvl, star);

    if (!next_up_exp_conf) {
        console.error('error -----  tech up lvl max');
        return false;
    } else {
        var now_exp = this.exp;
        var next_up_exp = next_up_exp_conf[0].exp;

        if (now_exp + exp_num >= next_up_exp) {
            var diff_exp = now_exp + exp_num - next_up_exp;
            this.exp = diff_exp;

            if (this.star + 1 >= max_star) {
                this.star = 0;
                this.lvl++;
            } else {
                this.star++;
            }
        } else {
            this.exp += exp_num;
        }
        return true;
    }
};

/* jshint unused:false */
unionTechSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};
///////////////////////////////////////////////////////////
/**
 * 公会成员信息
 * @type {mongoose}
 */
var userSchema = new mongoose.Schema({
    // 公会成员ID
    role_id: {
        type: Number,
        required: true
    },

    // 公会成员职位
    position: {
        type: Number,
        default: 3
    }
});

if (!userSchema.options.toJSON) {
    userSchema.options.toJSON = {};
}
/* jshint unused:false */
userSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

///////////////////////////////////////////////////////////

/**
 * 军团
 */
var unionGroupSchema = new mongoose.Schema({
    // 军团id
    union_id: {
        type: Number,
        required: true,
        unique: true,
        index: true,
        default: 0
    },

    // 军团公告
    union_announce: {
        type: String,
        default: ''
    },

    // 联盟创始人
    create_role_id: {
        type: Number,
        default: 0
    },

    // 联盟创建时间
    union_create_time: {
        type: Number,
        default: _time
    },

    // 军团名
    name: {
        type: String,
        default: 0,
        unique: true,
        require: true
    },

    // 联盟总贡献
    unix_contribution: {
        type: Number,
        default: 0
    },

    // 每日踢人次数
    kick_times: {
        type: Number,
        default: 0
    },

    // 聯盟旗幟
    union_flag: {
        type: Number,
        default: 0
    },

    // 限制加入等级
    limit_level: {
        type: Number,
        default: 0
    },

    // 军团当前经验
    union_exp: {
        type: Number,
        default: 0
    },

    // 军团等级
    lv: {
        type: Number,
        default: 1
    },

    // 申请人的角色id
    apply_list: [Number],

    // 上次刷新时间
    create_time: {
        type: Date,
        default: 0
    },

    // 上次刷新时间
    last_refresh_time: {
        type: Date,
        default: 0
    },

    // 每天申请公会限定一次
    join_Only_apply_list: [applyItemSchema],

    // 联盟成员列表
    union_user_list: [userSchema],

    // 联盟科技列表
    union_tech_list: {
        type: [unionTechSchema],
        default: _initialUnionTech
    },
});

unionGroupSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 根据职位获取公会成员个数
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionUserNumByPosition = function (position) {
    var total_num = 0;
    _.each(this.union_user_list, function (item) {
        if (item.position == position) {
            total_num++;
        }
    });
    return total_num;
};

/**
 * 获取tech_id
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getTechId = function (tech_type) {
    var tech_id = 0;
    if (!!tech_type) {

        _.some(this.union_tech_list, function (item) {
            if (item.tech_id == tech_type) {
                var tech_lvl = item.lvl;
                var tech_star = item.star;
                tech_star++;
                tech_lvl++;

                if (tech_lvl < 10) {
                    tech_lvl = 0 + tech_lvl.toString();
                }
                tech_id = item.tech_id.toString() + tech_lvl + tech_star.toString();
            }
        });
    }
    return tech_id;
};

/**
 * 联盟科技 tech_id 是否存在
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getTechEff = function (tech_type) {
    var self = this;
    var tech_id = self.getTechId(tech_type);
    if (tech_id === 0) {
        return 0;
    }

    var tech_conf = unionTechConf.getTechConf(tech_id);
    if (!tech_conf) {
        return 0;
    }

    return tech_conf[0].value;
};

/**
 * 联盟科技增加经验(这个函数，自动升级 到最大等级返回空)
 * @return {[type]} [description]
 */
unionGroupSchema.methods.addTechExp = function (tech_type, add_exp) {
    var item = null;
    _.some(this.union_tech_list, function (tech_item) {
        if (tech_item.tech_id == tech_type) {
            item = tech_item;
            return true;
        }
    });
    if (!!item) {
        item.addExp(add_exp);
        return true;
    } else {
        console.error('error  ---   max lvl or not find union tech conf  -------');
        return false;
    }
};

/**
 * 联盟科技类型返回item
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getTechItem = function (tech_type) {
    var item = null;
    _.some(this.union_tech_list, function (tech_item) {
        if (tech_item.tech_id == tech_type) {
            item = tech_item;
            return true;
        }
    });
    if (!!item) {
        return item;
    }
};

/**
 * 踢人
 * @return {[type]} [description]
 */
unionGroupSchema.methods.removeUserId = function (role_id) {
    _.some(this.union_user_list, function (item) {
        if (item.role_id == role_id) {
            item.remove();
            return true;
        }
    });
};

/**
 * 移除申请时间
 * @return {[type]} [description]
 */
unionGroupSchema.methods.removeJoinTime = function (role_id) {
    var now_time = moment().startOf('day');
    _.some(this.join_Only_apply_list, function (item) {
        if (item.role_id == role_id) {
            if (item.create_time < now_time) {
                item.remove();
            }
            return true;
        }
    });
};

/**
 * 移除申请人的角色id
 * @return {[type]} [description]
 */
unionGroupSchema.methods.removeApplyId = function (role_id) {
    this.apply_list.pull(role_id);
};

/**
 * 获取联盟名称
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionName = function () {
    return this.name;
};

/**
 * 获取联盟成员列表
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionUserList = function () {
    return this.union_user_list;
};

/**
 * 权限是否为公会长，或副会长
 * @return {[type]} [description]
 */
unionGroupSchema.methods.isBoss = function (role_id) {
    var isVaild = false;
    _.some(this.union_user_list, function (union_user_item) {
        if (union_user_item.role_id == role_id) {
            if (union_user_item.position <= 2) {
                isVaild = true;
                return true;
            }
        }
    });
    return isVaild;
};

/**
 * 获取角色职位
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUserPosition = function (role_id) {
    var position = 0;
    _.some(this.union_user_list, function (union_user_item) {
        if (union_user_item.role_id == role_id) {
            position = union_user_item.position;
            return true;
        }
    });
    return position;
};

/**
 * 升职
 * @return {[type]} [description]
 */
unionGroupSchema.methods.upgradPosition = function (role_id) {
    var isVaild = false;
    _.some(this.union_user_list, function (union_user_item) {
        if (union_user_item.role_id == role_id) {

            // 升职
            union_user_item.position--;
            isVaild = true;
            return true;
        }
    });
    return isVaild;
};

/**
 * 降职
 * @return {[type]} [description]
 */
unionGroupSchema.methods.downGradePosition = function (role_id) {
    var isVaild = false;
    _.some(this.union_user_list, function (union_user_item) {
        if (union_user_item.role_id == role_id) {

            // 升职
            union_user_item.position++;
            isVaild = true;
            return true;
        }
    });
    return isVaild;
};

/**
 * 移除联盟成员
 * @return {[type]} [description]
 */
unionGroupSchema.methods.removeUnionUser = function (remove_role_id) {
    _.some(this.union_user_list, function (union_user_item) {
        if (union_user_item.role_id == remove_role_id) {
            union_user_item.remove();
            return true;
        }
    });
};

/**
 * 增加成员信息
 * @return {[type]} [description]
 */
unionGroupSchema.methods.addUnionUser = function (role_id, position) {
    position = position || 3;
    var isVaild = false;
    _.some(this.union_user_list, function (role_item) {
        if (role_item.role_id == role_id) {
            isVaild = true;
            return true;
        }
    });

    if (!isVaild) {
        this.union_user_list.push({
            role_id: role_id,
            position: position
        });
    }
};

/**
 * 获取当天是否申请过该公会列表
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getJoinOnlyApplyList = function () {
    return this.join_Only_apply_list;
};

/**
 * 是否可以申请公会（每天只能申请一次）
 * @return {[type]} [description]
 */
unionGroupSchema.methods.isJoinOnlyApplyList = function (role_id) {
    var isVaild = true;
    var now_time = moment().startOf('day');
    _.some(this.getJoinOnlyApplyList(), function (value) {
        if (value.role_id == role_id) {
            if (value.create_time >= now_time) {
                isVaild = false;
                return true;
            }
        }
    });
    return isVaild;
};

/**
 * 加入当天申请公会记录(如果有就刷新时间，如果没有就加入记录)
 * @return {[type]} [description]
 */
unionGroupSchema.methods.addJoinOnlyApplyList = function (role_id) {
    var isVaild = false;
    _.some(this.join_Only_apply_list, function (value) {
        if (value.role_id == role_id) {
            value.create_time = Date.now();
            isVaild = true;
            return true;
        }
    });
    if (!isVaild) {
        this.join_Only_apply_list.push({
            role_id: role_id,
            create_time: Date.now()
        });
    }
};

/**
 * 设置公会宣告
 * @return {[type]} [description]
 */
unionGroupSchema.methods.setUnionAnnounce = function (union_announce) {
    this.union_announce = union_announce;
};

/**
 * 设置公会名字
 * @return {[type]} [description]
 */
unionGroupSchema.methods.setUnionName = function (name) {
    this.name = name;
};

/**
 * 获取公会id
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionId = function () {
    return this.union_id;
};

/**
 * 設置聯盟旗幟
 * @return {[type]} [description]
 */
unionGroupSchema.methods.setUnionFlag = function (union_flag_id) {
    this.union_flag = union_flag_id;
};

/**
 * 設置聯盟加入等級
 * @return {[type]} [description]
 */
unionGroupSchema.methods.setUnionJoinLimirLevel = function (limit_level) {
    this.limit_level = limit_level;
};

/**
 * 獲取聯盟限制等級
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionJoinLimirLevel = function () {
    return this.limit_level;
};

/**
 * 获取公会等级
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionLv = function () {
    return this.lv;
};

/**
 * 获取每日公会踢人次数
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getUnionKickTimes = function () {
    return this.kick_times;
};

/**
 * 每日公会踢人次数
 * @return {[type]} [description]
 */
unionGroupSchema.methods.addUnionKickTimes = function () {
    this.kick_times++;
};

/**
 * 增加军团经验
 * @return {[type]} [description]
 */
unionGroupSchema.methods.addUnionExp = function (exp_num) {
    this.union_exp += exp_num;
    var exp = this.union_exp;
    var max_lv = 1;
    dataApi.union.each(function (union_item) {
        if (exp >= union_item.exp) {
            max_lv = union_item.id;
        }
    });

    // 判断是否Vip等级升级
    if (this.lv != max_lv) {
        this.lv = max_lv;
    }
};

/**
 * 请求的用户
 * @param {[type]} role_id [description]
 */
unionGroupSchema.methods.getApplyList = function () {
    return this.apply_list;
};

/**
 * 请求的用户数量
 * @param {[type]} role_id [description]
 */
unionGroupSchema.methods.getApplyNum = function () {
    return _.size(this.apply_list);
};

/**
 * 添加请求的用户
 * @param {[type]} role_id [description]
 */
unionGroupSchema.methods.addApply = function (role_id) {
    if (_.indexOf(this.apply_list, role_id) !== -1) {
        return false;
    }
    this.apply_list.push(role_id);
    return true;
};

/**
 * 重置军团
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
unionGroupSchema.methods.reset = function () {
    this.kick_times = 0;
    this.last_refresh_time = moment();
};

/**
 * 获取上次刷新时间
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
unionGroupSchema.methods.getLastRefreshTime = function () {
    return this.last_refresh_time;
};

/**
 * 同意加入请求
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
unionGroupSchema.methods.acceptApply = function (role_id) {
    if (!this.deleteApply(role_id)) {
        return false;
    }
    return true;
};

/**
 * 删除请求
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
unionGroupSchema.methods.deleteApply = function (role_id) {
    if (_.indexOf(this.apply_list, role_id) != -1) {
        this.apply_list.pull(role_id);
        return true;
    }
    return false;
};

/**
 * 联盟刷新
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
unionGroupSchema.methods.refresh = function (role_id) {
    this.kick_times = 3;
};

unionGroupSchema.plugin(autoIncrement.plugin, {
    model: 'UnionGroupSchema',
    field: 'union_id',
    startAt: 10000
});

/**
 * 获取修改
 * @return {[type]} [description]
 */
unionGroupSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
unionGroupSchema.methods.push = function () {
    this.pushModify();
};

unionGroupSchema.methods.pushModify = function () {
    var change = this.getLastChange();
    // var role_id_list = [];
    // _.some(this.union_user_list, function (role_item) {
    //     role_id_list.push(role_item.role_id);
    // });
    unionGroupMgr.sendUnionGroupChangedMulti(
        this.union_id,
        change,
        function (err, fails) {
            if (err) {
                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );

};

unionGroupSchema.methods.pushModifyToRole = function (role_id) {
    unionGroupMgr.sendUnionGroupChanged(
        role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!unionGroupSchema.options.toJSON) {
    unionGroupSchema.options.toJSON = {};
}
/* jshint unused:false */
unionGroupSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

mongoose.model('UnionGroup', unionGroupSchema);
